﻿using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using XfTech.SmartTms.Data;
using Serilog;
using Volo.Abp;

namespace XfTech.SmartTms.DbMigrator
{
    /// <summary>
    /// 这是一个后台任务，项目启动的时候会自动执行里面的功能
    /// </summary>
    public class DbMigratorHostedService : IHostedService
    {
        private readonly IHostApplicationLifetime _hostApplicationLifetime;
        private readonly IConfiguration _configuration;

        public DbMigratorHostedService(IHostApplicationLifetime hostApplicationLifetime, IConfiguration configuration)
        {
            _hostApplicationLifetime = hostApplicationLifetime;
            _configuration = configuration;
        }

        /// <summary> 
        /// 开始执行   （async/await 两个关键字，异步编程） 异步方法的方法名以Async结尾，比如 GetStudentAsync
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            using (var application = AbpApplicationFactory.Create<SmartTmsDbMigratorModule>(options =>
            {
                options.Services.ReplaceConfiguration(_configuration);
                options.UseAutofac(); //自动集成了AutoFac
                options.Services.AddLogging(c => c.AddSerilog());
            }))
            {
                application.Initialize();

                await application   //await  等待异步方法的完成
                    .ServiceProvider
                    .GetRequiredService<SmartTmsDbMigrationService>()
                    .MigrateAsync();     //用SmartTmsDbMigrationService服务进行数据库迁移

                application.Shutdown();

                _hostApplicationLifetime.StopApplication();
            }
        }

        /// <summary>
        /// 结束执行
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
    }
}
